const api = require('../../../config/api.js');
const app = getApp();
let that;
Page({
  data: {
    ImgRootUrl: app.globalData.ImgRootUrl,
    cat_id: 0,  //商品分类id
    collectList: []
  },
  onLoad: function (options) {
    that = this;
    this.getCollectList();
  },
  onReady: function () {

  },
  onShow: function () {

  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  //获取收藏列表
  getCollectList() {
    app.util.wxrequest(api.CollectList, { cat_id: that.data.cat_id}).then(function (res) {
      if (res.errno === 0) {
        that.setData({
          collectList: res.data
        });
      } else {
        app.util.showToast(res.error);
        that.switchTab();
      }
    });
  },
  //跳转商品详情 或 删除收藏的商品(触摸时间大于350ms)
  openGoods(event) {
    let i = event.currentTarget.dataset.i; //索引
    let goodsId = event.currentTarget.dataset.id; //商品id
    let name = event.currentTarget.dataset.name; //商品名字
    //触摸时间
    var touchTime = that.data.touch_end - that.data.touch_start;
    //如果按下时间大于350为长按
    if (touchTime > 350) {
      wx.showModal({
        title: '取消收藏？',
        content: name,
        success: function (res) {
          if (res.confirm) {            
            app.util.wxrequest(api.CollectAddOrDelete, { goods_id: goodsId }, 'POST').then(function (res) {
              if (res.errno === 0) {
                console.log(res.data);
                let _collectList = that.data.collectList.filter(function(v,index){
                  if(index != i){
                    return v;
                  }
                });
                //更新视图
                that.setData({
                  collectList: _collectList
                });
                //判断收藏夹是否为空
                if (collectList.length <=0){
                  app.util.showToast('收藏夹为空');
                  that.switchTab();
                } else {
                  wx.showToast({
                    title: '取消成功',
                    icon: 'success',
                    mask: true,
                    duration: 2000
                  });
                }
              }
            });
          }
        }
      })
    } else {      
      wx.navigateTo({
        url: '/pages/goods/goods?id=' + goodsId,
      });
    }  
  },
  //按下事件开始  
  touchStart: function (e) {
    that.setData({
      touch_start: e.timeStamp
    })
    //console.log(e.timeStamp + '- touch-start')
  },
  //按下事件结束  
  touchEnd: function (e) {
    that.setData({
      touch_end: e.timeStamp
    })
    //console.log(e.timeStamp + '- touch-end')
  },
  //延时跳转
  switchTab(){
    that.timer = setTimeout(function () {
      clearTimeout(that.timer);
      wx.switchTab({
        url: '/pages/ucenter/index/index'
      });
    }, 1500);
  },
})